//
//  CYXFourViewController.m
//   
//
//  Created by Macx on 15/9/4.
//  Copyright (c) 2015年 CYX. All rights reserved.
//

#import "CYXFourViewController.h"
#import "LanguageSelectTableViewController.h"
#import "AccountSafeMenuController.h"
#import "ShareViewController.h"
#import "MyQRCodeViewController.h"
#import "UserInfoTableViewController.h"
#import "CYXSettingItem.h"
#import "CYXGroupItem.h"
#import "ProfileTabHeader.h"
#import "WalletMainTableViewCell.h"
#import "ProfileTableViewCell.h"
#import "WalletTabViewController.h"
#import "UpdateInfoView.h"
#import "CYXBaseRequest.h"
#import "VersionModel.h"
#import "TabMenuItem.h"
#import "LogOnViewController.h"
#import "CYXNavigationController.h"
#import "WalletMainModel.h"
#import "UserInfoModel.h"


@interface CYXFourViewController ()

@property (strong, nonatomic) NSMutableArray * groups;/**< 组数组 描述TableView有多少组 */

/// <#注释#>
/// <#注释#>
@property (nonatomic, strong) NSArray *menuList;

/// <#注释#>
@property (nonatomic, strong) TabMenuItem *updateItem;
@property (nonatomic, strong) TabMenuItem *languageItem;

/// <#注释#>
@property (nonatomic, strong) ProfileTabHeader *header;

/// <#注释#>
@property (nonatomic, strong) UIImage *userIcon;

@end

@implementation CYXFourViewController
/** groups 数据懒加载*/
- (NSMutableArray *)groups
{
    if (!_groups) {
        _groups = [NSMutableArray array];
    }
    return _groups;
}


//- (instancetype)init{
//
//    // 设置tableView的分组样式为Group样式
//    return [self initWithStyle:UITableViewStyleGrouped];
//}

- (void)viewDidLoad {
    self.isIgnoreLogon = YES;
    [super viewDidLoad];
    // 配置菜单信息
    [self configMenuinfo];
    [self configNewVersion];
    
    [LCNotifiCenter addObserver:(self) selector:(@selector(getUserInfo)) name:(@"UserInfoNeedUpdate") object:nil];
    [LCNotifiCenter addObserver:(self) selector:(@selector(logOnNewUser)) name:(@"UserLogOnSuccess") object:nil];
    [LCNotifiCenter addObserver:(self) selector:(@selector(resetUserInfo)) name:(@"UserLogOutSuccess") object:nil];
    [LCNotifiCenter addObserver:(self) selector:(@selector(configNewVersion)) name:(@"GetAppVersionSuccess") object:nil];
    [LCNotifiCenter addObserver:(self) selector:(@selector(refreshWallet)) name:(@"WalletModelSuccess") object:nil];
    
    
}

- (void)resetUserInfo{
    kAppDelegate.curUser = nil;
    kAppDelegate.walletM = nil;
    [self.tableView reloadData];
}

- (void)logOnNewUser{
    kAppDelegate.walletM = nil;
    [self.tableView reloadData];
    [self getUserAssets];
    [self getUserInfo];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getUserAssets];
    [self getUserInfo];
}

- (void)configMenuinfo{
    NSString *curVerinfo = [NSString stringWithFormat:@"%@%@",LCLocalString(@"cru_ver"),APPVersionCode];
    self.updateItem.subTitle = LCLocalString(@"update_ljgx");
   NSArray *defaultMenuInfo = @[
    @{@"title":LCLocalString(@"my_qrcode"),@"subTitle":@"",@"icon":@"menu_erweima",@"ishideArr":@(NO)},
    @{@"title":LCLocalString(@"share_app"),@"subTitle":@"",@"icon":@"menu_fenxiang",@"ishideArr":@(NO)},
    @{@"title":LCLocalString(@"account_security"),@"subTitle":@"",@"icon":@"menu_anquan",@"ishideArr":@(NO)},
    @{@"title":LCLocalString(@"language"),@"subTitle":[LanguageManager userLanguageShowName],@"icon":@"menu_yuyan",@"ishideArr":@(NO)},
      @{@"title":LCLocalString(@"check_update"),@"subTitle":curVerinfo,@"icon":@"menu_gengxin",@"ishideArr":@(NO)}];
    self.menuList = [TabMenuItem mj_objectArrayWithKeyValuesArray:defaultMenuInfo];
    for (TabMenuItem *item in self.menuList) {
        NSInteger index = [self.menuList indexOfObject:item];
        if(index == 0){
            item.indexFlag = -1;
        }else if (index == self.menuList.count - 1){
            item.indexFlag = 1;
        }else{
            item.indexFlag = 0;
        }
        if ([item.icon isEqualToString:@"menu_gengxin"]) {
            self.updateItem = item;
        }
        if ([item.icon isEqualToString:@"menu_yuyan"]) {
            self.languageItem = item;
        }
    }
}

- (void)setupUI{
    [super setupUI];
    self.tableView.backgroundColor = MainColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.header = [[ProfileTabHeader alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 103)];
    LRWeakSelf(self);
    self.header.actionBlock = ^(NSInteger actionFlag) {
        if (!kAppDelegate.curUser) {
            [weakself goToLogOn];
            return;
        }
       
        if (actionFlag) {
            [weakself pushUserInfoVC];
//            [LanguageManager setUserlanguage:@"zh-Hans"];
        }else{
            [weakself pushUserInfoVC];
//            [weakself goToLogOn];
        }
    };
    
    self.tableView.tableHeaderView = self.header;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"WalletMainTableViewCell" bundle:nil] forCellReuseIdentifier:@"WalletMainTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ProfileTableViewCell" bundle:nil] forCellReuseIdentifier:@"ProfileTableViewCell"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
}


#pragma mark - TableView的数据源代理方法实现

/**
 *  返回有多少组的代理方法
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}
/**
 *  返回每组有多少行的代理方法
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
 
    
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return self.menuList.count;
            break;
            
        default:
            break;
    }
    return 0;
}

/**
 *  返回每一行Cell的代理方法
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *ID1 = @"UITableViewCell";
    static NSString *ID2 = @"WalletMainTableViewCell";
    static NSString *ID3 = @"ProfileTableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID1];
    switch (indexPath.section) {
        case 0:
        {
            WalletMainTableViewCell *walletCell = [tableView dequeueReusableCellWithIdentifier:ID2];
            [walletCell refreshWith:kAppDelegate.walletM];
            cell = walletCell;
        }
            break;
        case 1:
        {
            ProfileTableViewCell *profileCell = [tableView dequeueReusableCellWithIdentifier:ID3];
            [profileCell refreshWithItem:self.menuList[indexPath.row]];
            cell = profileCell;
        }
            break;
            
        default:
            break;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
            return 115.0f;
            break;
        case 1:
            return 55.0f;
            break;
            
        default:
            break;
    }
    return CGFLOAT_MIN;
}




- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!kAppDelegate.curUser) {
        [self goToLogOn];
        return;
    }
    if(indexPath.section == 0){
        CYXLog(@"钱包 push");
        WalletTabViewController *vc = [[WalletTabViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if(indexPath.section == 1){
        TabMenuItem *item = self.menuList[indexPath.row];
        CYXLog(@"%@",item.title);
        if (indexPath.row == 0) {
            CYXLog(@"二维码");
            MyQRCodeViewController *vc = [[MyQRCodeViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        } else if (indexPath.row == 1) {
            CYXLog(@"分享");
            ShareViewController *vc = [[ShareViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 2) {
            CYXLog(@"安全");
            
            AccountSafeMenuController *vc = [[AccountSafeMenuController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 3) {
            CYXLog(@"语言");
            LanguageSelectTableViewController *vc = [[LanguageSelectTableViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 4) {
            CYXLog(@"检查更新");
            [self showUpdateView];
        }
        
    }
}

- (void)showUpdateView{
    if (!kAppDelegate.versionM) {
        return;
    }
    
    UpdateInfoView *view = [[UpdateInfoView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT)];
    [view refreshWithModel:kAppDelegate.versionM];
    LRWeakSelf(self);
    view.actionBlock = ^(NSInteger index) {
        CYXLog(@"%zd",index);
        if(index == 1 && kAppDelegate.versionM.isNeedUpdate){
            NSString *updateUrl = kAppDelegate.versionM.downloadUrl;
            if (!updateUrl || !updateUrl.length) {
                updateUrl = AppUpdateUrl;
            }
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:updateUrl]];
        }
    };
    
    [view showInView:self.navigationController.view];
}

- (void)getUserAssets{
//    NSDictionary *param = @{@"name":@"",@"hideLittleAsset":@(NO)};
    [CYXBaseRequest postWithUrl:API_getUserAssets param:nil resultClass:[WalletMainModel class] success:^(id res) {
        if ([res isEqual: RequestErrorCode]) {
            
        }else{
            kAppDelegate.walletM = res;
            LCPostNotification(@"WalletModelSuccess");
            [self.tableView reloadData];
        }
        
        CYXLog(@"%@",res)
    } failure:^(NSError *error) {
        CYXLog(@"%@",error)
    }];
}

- (void)getUserInfo{
    [CYXBaseRequest postWithUrl:API_getUserInfo param:nil resultClass:[UserInfoModel class] success:^(id res) {
        if ([res isEqual: RequestErrorCode]) {
            
        }else{
            kAppDelegate.curUser = res;
            kAppDelegate.curUser.icon = self.userIcon;
//            if(!self.userIcon){
                [self getUserIcon];

//            }else{
//                kAppDelegate.curUser.icon = self.userIcon;
//            }
            [self.header refresh];
            
        }
        
        CYXLog(@"%@",res)
    } failure:^(NSError *error) {
        CYXLog(@"%@",error)
    }];
}

- (void)getUserIcon{
    [CYXBaseRequest postWithUrl:API_getUserIcon param:nil resultClass:[UIImage class] success:^(id res) {
        if ([res isEqual: RequestErrorCode]) {
            
        }else{
            self.userIcon = res;
            kAppDelegate.curUser.icon = res;
            LCPostNotification(@"UserInfoUpdated");
            [self.header refresh];
        }
        CYXLog(@"%@",res)
    } failure:^(NSError *error) {
        CYXLog(@"%@",error)
    }];
}

- (void)configNewVersion{
    if(kAppDelegate.versionM.isNeedUpdate){
        self.updateItem.subTitle = LCLocalString(@"update_ljgx");
        [self.tableView reloadData];
    }
}

#pragma mark -

- (void)pushUserInfoVC{
    UserInfoTableViewController *vc = [[UserInfoTableViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)refreshWallet{
    [self.tableView reloadData];
}



@end
